<template>
  <div>
    <!-- 明细布局 -->
    <div v-if="!showBillList">
      <!-- 顶部筛选区 -->
      <el-form :inline="true" class="filter-form">
        <el-form-item label="">
          <el-input v-model="filters.followOrderNumber" placeholder="跟单编号" />
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="filters.documentCode" placeholder="单据编码" />
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="filters.materialName" placeholder="物料名称" />
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="filters.startDate"
            type="date"
            placeholder="开始日期"
          />
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="filters.endDate"
            type="date"
            placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区 -->
      <div class="btn-group" style="margin: 10px 0;">
        <el-button type="primary" @click="showBillList = true">单据</el-button>
        <el-button>查询所有</el-button>
        <el-button type="success" @click="addOutSourRelease()">新增</el-button>
        <el-button type="warning">导出</el-button>
      </div>

      <!-- 数据表格区 -->
      <el-table :data="tableData" style="width: 100%;" empty-text="暂无数据">
        <el-table-column prop="index" label="序号" width="60" />
        <el-table-column prop="followOrderNumber" label="跟单编号" />
        <el-table-column prop="documentCode" label="单据编号" />
        <el-table-column prop="documentStatus" label="单据状态" />
        <el-table-column prop="outsourcingOrderNumber" label="委外订单号" />
        <el-table-column prop="supplier" label="供应商" />
        <el-table-column prop="materialName" label="物料名称" />
        <el-table-column prop="materialCode" label="物料编码" />
        <el-table-column prop="warehouse" label="发料仓库" />
        <el-table-column prop="outsourcingQuantity" label="发料数量" />
        <el-table-column prop="documentDate" label="单据日期" />
      </el-table>
    </div>

    <!-- 单据布局 -->
    <div v-else>
      <!-- 顶部按钮组 -->
      <div class="bill-btn-group" style="margin-bottom: 10px;">
        <el-button type="primary" @click="showBillList = false">明细</el-button>
        <el-button>查询所有</el-button>
        <el-button type="success">新增</el-button>
        <el-button type="danger" @click="DeleteGetOutID(selectedIds)">删除</el-button>
        <el-button type="success">审核</el-button>
        <el-button type="warning">反审核</el-button>
      </div>
      <!-- 单据搜索栏 -->
      <div class="bill-search-bar" style="margin-bottom: 10px;" >
        <el-input placeholder="单据编码" v-model="billFilters.DocumentCode" style="width: 180px; margin-right: 10px;" />
        <el-select v-model="billFilters.DocumentStatus" placeholder="单据状态" style="width: 150px; margin-right: 10px;">
          <el-option label="开立" value="开立" />
          <el-option label="审核" value="审核" />
        </el-select>
        <el-select v-model="billFilters.BusinessStatus" placeholder="业务状态" style="width: 150px; margin-right: 10px;">
          <el-option label="正常" value="正常" />
          <el-option label="挂起" value="挂起" />
        </el-select>
        <el-date-picker
          v-model="billFilters.BeginTime"
          type="date"
          placeholder="开始日期"
          style="width: 140px; margin-right: 5px;"
        />
        -
        <el-date-picker
          v-model="billFilters.EndTime"
          type="date"
          placeholder="结束日期"
          style="width: 140px; margin-right: 10px;"
        />
        <el-button type="primary" icon="el-icon-search" @click="onBillSearch">搜索</el-button>
      </div>
      <!-- 单据表格 -->
      <el-table :data="billTableData" border style="width: 100%;" empty-text="暂无数据" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="documentCode" label="单据编码" />
        <el-table-column prop="documentDate" label="单据日期" />
        <el-table-column prop="documentStatus" label="单据状态" />
        <el-table-column prop="businessType" label="业务类型" />
        <el-table-column prop="businessStatus" label="业务状态" />
        <el-table-column prop="auditDate" label="审核日期" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="success" link size="small">查看</el-button>
            <el-button type="primary" link  size="small" @click="UpdateOutSourRelease(scope.row)">编辑</el-button>
            <el-button type="danger" link size="small"@click=deleteBill(scope.row.id)>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      v-model:current-page="billFilters.pageindex"
      v-model:page-size="billFilters.pagesize"
      :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="billFilters.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { KongaUrl } from '@/axios/axiosHelp'
import axios from 'axios'
import { ElMessage,ElMessageBox } from 'element-plus'
import { el } from 'element-plus/es/locales.mjs'

const showBillList = ref(false) // 默认显示明细

// 明细布局的筛选
const filters = reactive({
  followOrderNumber: '',
  materialName: '',
  documentCode: '',
  startDate: '',
  endDate: '',
  pageindex: 1,
  pagesize: 15,
  totalpage: 0,
  totalcount: 0,
})
const tableData = ref([])

// 单据布局的筛选
const billFilters = reactive({
  DocumentCode: '',
  DocumentStatus: '',
  BusinessStatus: '',
  BeginTime: '',
  EndTime: '',
  pageindex: 1,
  pagesize: 15,
  totalpage: 0,
  totalcount: 0,
})
const billTableData = ref([])

const router = useRouter()

onMounted(() => {
  getOutSourReleaseList();
  getBillList();
})
 //翻页函数
 const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  billFilters.pagesize=val;
  getBillList();
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  billFilters.pageindex=val;
  getBillList();
}


const getOutSourReleaseList = () => {
  KongaUrl({
    url: '/weiwaidu/api/OutSourc/QueryOutSourRelease',
    method: 'get',
    params: {
      DocumentCode: filters.documentCode,
      MaterialName: filters.materialName,
      FollowOrderNumber: filters.followOrderNumber,
      BeginTime: filters.startDate,
      EndTime: filters.endDate,
      pageindex: filters.pageindex,
      pagesize: filters.pagesize
    }
  }).then(res => {
    if (res.data.code == 0) {
      tableData.value = res.data.list
      filters.totalpage = res.data.totalpage
      filters.totalcount = res.data.totalcount
    }
  })
}

const getBillList = () => {
  // 这里可以根据实际接口调整
  KongaUrl({
    url:'/weiwaidu/api/OutSourc/QueryOutSourReleaseDan',
    method:'get',
    params:{
      DocumentCode:billFilters.DocumentCode,
      DocumentStatus:billFilters.DocumentStatus,
      BusinessStatus:billFilters.BusinessStatus,
      BeginTime:billFilters.BeginTime,
      EndTime:billFilters.EndTime,
      pageindex:billFilters.pageindex,
      pagesize:billFilters.pagesize
    }
  })
  .then(res=>{
    if(res.data.code==0){
      billTableData.value = res.data.list // 这里应为接口返回的单据数据
      console.log(billTableData.value)
      billFilters.totalpage = res.data.totalpage
      billFilters.totalcount = res.data.totalcount
    }
  })
}

const addOutSourRelease = () => {
  router.push("/AddOutSourRelease")
}
const onSearch = () => {
  getOutSourReleaseList()
}
const onBillSearch = () => {
  getBillList()
}

const deleteBill=(id)=>{
  ElMessageBox.confirm(
    '您确定要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(()=>{
    KongaUrl({
    url:'/weiwaixie/api/Outsour/DeleteOutsourMateria',
    method:'post',
    data:{
      id:id
    }
  })
  .then(res=>{
    if(res.data.code==101){
      ElMessage.success('删除成功');
      getBillList();
    }
  })
  })
  .catch(()=>{
    ElMessage.info('已取消操作');
  })
 
}
const UpdateOutSourRelease=(row)=>{
  router.push({
    path:'/UpdateOutSourRelease',
    query:{...row}
  })
}
const selectedIds = ref([])
// 选择项变化
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
  console.log('选中的数据', selectedIds.value)
}
// 批量删除操作
const DeleteGetOutID = (id) => {
  console.log('选中批量的数据', id.length)
  console.log('选中的数据', id)
  
  if(id.length === 0){
    ElMessage.error("请选择数据")
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${id.length} 条数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 修正后的请求方式
      const response = await KongaUrl({
        url: '/weiwaixie/api/Outsour/DeleteALLOutsourMateria',
        method: 'post',
        data:{
          Id:id
        }
      })
      
      if(response.data.code == 101) {
        ElMessage.success('删除成功')
        // 刷新数据
        getBillList();
      } 
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}
</script>

<style scoped>
.filter-form {
  margin-bottom: 10px;
}
.btn-group, .bill-btn-group {
  display: flex;
  gap: 10px;
}
</style>